package org.inet.minispring.bean.beanregistry;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

public class DefaultSingletonBeanRegistry implements SingletonBeanRegistry {

    protected final List<String> beanNames = new ArrayList<>();

    // bean name -> singleton
    protected final Map<String, Object> singletons = new ConcurrentHashMap<>(256);

    @Override
    public void registerSingleton(String beanName, Object singletonObject) {
        synchronized (this) {
            singletons.put(beanName, singletonObject);
            beanNames.add(beanName);
        }
    }

    protected void removeSingleton(String beanName) {
        synchronized (this) {
            this.beanNames.remove(beanName);
            this.singletons.remove(beanName);
        }
    }

    @Override
    public Object getSingleton(String beanName) {
        return singletons.get(beanName);
    }

    @Override
    public boolean containsSingleton(String beanName) {
        return singletons.containsKey(beanName);
    }

    @Override
    public String[] getSingletonNames() {
        return (String[]) beanNames.stream().filter(Objects::nonNull).toArray();
    }
}
